<template>
  <div id="canvas-test">
    <div class="app-header">
      <h4>测试 Canvas 绘图</h4>
    </div>
    <div class="content">
      <canvas id="c" :width="width" :height="height" style="border:1px solid #ccc;"></canvas>
      <div class="controls">
        <zi-button @click="addImageToCanvas">添加图片</zi-button>
        <zi-button @click="addTextToCanvas">添加文字</zi-button>
        <zi-button @click="saveCanvasImage">保存</zi-button>
      </div>
    </div>

    <zi-dialog
      v-model="dialog1.visible"
      cancel="取消"
      done="确认"
      :title="dialog1.title"
      :beforeDone="confirmDialog"
      :closeByModal="false"
    >
      <p v-html="dialog1.text"></p>
    </zi-dialog>

    <zi-dialog
      v-model="textForm.visible"
      cancel="取消"
      done="确认"
      title="请输入文字"
      :beforeDone="confirmText"
      :closeByModal="false"
    >
      <p>
        <zi-input value="" size="small" v-model="textForm.text"></zi-input>
      </p>
    </zi-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
  import canvasBuffer from '@/services/electron-canvas-to-buffer'
  import fs from 'fs'
  import path from 'path'
  import remoteTools from '@/services/remoteTools'

  export default {
    name: 'canvas-test',
    data () {
      return {
        width: 360,
        height: 640,
        bgImgUrl: 'static/imgs/template1-cover.png',
        dialog1: {
          visible: false,
          title: '',
          text: '检查到版本更新，请点击下载',
        },
        textForm: {
          visible: false,
          text: '',
        },
        __canvas: null,
        version: '0.1',

      }
    },
    mounted: function() {
      this.initCanvas();
    },
    methods: {
      confirmDialog() {

      },
      confirmText() {
        console.log(this.textForm.text);
        if (!this.textForm.text) {
          this.$Toast.show({
            type: 'danger',
            text: '文字内容不能为空',
            duration: 4
          })
          return;
        }
        this.textForm.visible = false;
        if (this.__canvas) {
          var text = this.textForm.text
          var itext = new fabric.Text(text, {
            left: 100,
            top: 150,
            fill: '#666666',
            // fontFamily: '',
            fontSize: 20,
          });

          this.__canvas.add(itext);
          this.__canvas.setActiveObject(itext);
        }
      },
      initCanvas() {
        var canvas = this.__canvas = new fabric.Canvas('c');
        // set background color
        canvas.setBackgroundImage(this.bgImgUrl, canvas.renderAll.bind(canvas), {
            width: 720,
            height: 1280,
            repeat: 'no-repeat',
            originX: 'left',
            originY: 'top',
            scaleX: 0.5,
            scaleY: 0.5,
        });
        // create a rect object
        var deleteIcon = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E";

        var img = document.createElement('img');
        img.src = deleteIcon;

        function deleteObject(eventData, target) {
          var canvas = target.canvas;
          canvas.remove(target);
          canvas.requestRenderAll();
        }

        function renderIcon(ctx, left, top, styleOverride, fabricObject) {
          if (!this.getVisibility(fabricObject)) {
            return;
          }
          var size = this.cornerSize;
          ctx.save();
          ctx.translate(left, top);
          ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
          ctx.drawImage(img, -size/2, -size/2, size, size);
          ctx.restore();
        }
        fabric.Object.prototype.controls.deleteControl = new fabric.Control({
          position: { x: 0.5, y: -0.5 },
          offsetY: 0,
          cursorStyle: 'pointer',
          mouseUpHandler: deleteObject,
          render: renderIcon,
          cornerSize: 20
        });
      },
      addRectToCanvas() {
        if (this.__canvas) {
          var rect = new fabric.Rect({
            left: 100,
            top: 50,
            fill: 'yellow',
            width: 200,
            height: 100,
            objectCaching: false,
            transparentCorners: false,
            cornerColor: 'blue',
            stroke: 'lightgreen',
            strokeWidth: 4,
            cornerStyle: 'circle'
          });

          this.__canvas.add(rect);
          this.__canvas.setActiveObject(rect);
        }
      },
      addImageToCanvas() {
        var _this = this;
        var imgFile = remoteTools.chooseSingleImage();
        var nativeImage = require('electron').nativeImage;
        var img = nativeImage.createFromPath(imgFile);
        var imgSize = img.getSize();
        var scale = 100 / imgSize.width;
        // console.log(imgSize);
        if (this.__canvas) {
          fabric.Image.fromURL(img.toDataURL(), function(oImg) {
            oImg.scale(scale).set({
              left: 100,
              top: 100,
            });
            _this.__canvas.add(oImg);
            _this.__canvas.setActiveObject(oImg);
          });
        }
      },
      addTextToCanvas() {
        this.textForm = {
          visible: true,
          text: '',
        };
      },
      saveCanvasImage() {
        this.__canvas.discardActiveObject().renderAll(); // 取消 canvas 当前选中的对象
        var _this = this;
        var canvas = document.getElementById('c');
        // as a buffer
        var buffer = canvasBuffer(canvas, 'image/png');
        let outputPath = path.resolve(remoteTools.getDownloadDir(), 'video-batch-maker', `canvasBuffer.png`);

        // write canvas to file
        fs.writeFile(outputPath, buffer, function (err) {
          if (err) {
            throw err
          } else {
            alert('保存成功');
          }
        })
      }
    }
  }
</script>

<style>
  @import url('~@/assets/styles/main.css');
  
</style>
